<%@ page language="java" contentType="text/html; charset=windows-1255"
    pageEncoding="windows-1255"%>

<%@page import="java.sql.PreparedStatement"%>
<%@page import="utils.DBConnector"%>
<%@page import="utils.Printer"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.Statement"%>


<%	
if (request.getSession(false) == null || request.getSession(false).getAttribute("username") == null){
	response.sendError(HttpServletResponse.SC_FORBIDDEN, "Please login first");
	return;
}
		
%>

<% 
 
boolean isEmpty;
DBConnector dbConn = new DBConnector();

PreparedStatement stmnt = dbConn.getConnection().prepareStatement(
			"SELECT course_name, credit_points, group_number, capacity - (SELECT COUNT(username) FROM user_courses WHERE course_name = c.course_name) AS registered " 		+  
			"FROM courses c " 												+  
			"WHERE is_active = TRUE AND" 									+ 
			"    (c.course_name   like concat('%', ?, '%') or ? = '' ) "	+
			"and (c.description   like concat('%', ?, '%') or ? = '' ) "	+
			"and (c.group_number  = ? or ? = '')  "							+
			"and (c.credit_points = ? or ? = '') "							+ 
			"and (c.course_name, ? ) not in "								+ 
			"(select uc.course_name, uc.username from user_courses uc); "
			);

stmnt.setString(1, request.getParameter("course_name"));
stmnt.setString(2, request.getParameter("course_name"));
stmnt.setString(3, request.getParameter("course_description"));
stmnt.setString(4, request.getParameter("course_description"));
stmnt.setString(5, request.getParameter("course_group"));
stmnt.setString(6, request.getParameter("course_group"));
stmnt.setString(7, request.getParameter("credit_points"));
stmnt.setString(8, request.getParameter("credit_points"));
stmnt.setString(9, request.getSession(false).getAttribute("username").toString());


ResultSet res = stmnt.executeQuery();
isEmpty = !res.next(); //will be true if reultset is empty
res.beforeFirst();
%>

<%
	if (isEmpty){
	out.println("<h2>Sorry, no matches...</h2>");
}

else {
	out.println("<h2>Results</h2>");
	Printer.printCourses(out, res, "AddCourseUser", "user_course_details.jsp", "Register to Course", true, false, request.getSession(false).getAttribute("username").toString() );
}
dbConn.close();
%>

